package cn.itsource.pay.service.impl;

import cn.itsource.dto.PayDto;
import cn.itsource.pay.constant.AlipayConfig;
import cn.itsource.pay.domain.AlipayBean;
import cn.itsource.pay.domain.TPayAlipayInfo;
import cn.itsource.pay.mapper.PayAlipayInfoMapper;
import cn.itsource.pay.service.IAlipayInfoService;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class AlipayInfoServiceImpl implements IAlipayInfoService {

    @Autowired
    private PayAlipayInfoMapper payAlipayInfoMapper;

    public TPayAlipayInfo loadByAppid(String app_id) {
        return payAlipayInfoMapper.loadByAppid(app_id);
    }

    public String goBuy(PayDto dto) {
        if (StringUtils.isAnyBlank(dto.getSubject(), dto.getSubjectDesc()) || dto.getMoney() == null || dto.getShopId() == null) {
            System.out.println(">>>>>>>>>>>>>缺少必传参数");
            return "<h1>缺少必传参数</h1>";
        }
        try {
            //根据店铺id查询支付信息
            TPayAlipayInfo alipayInfo = payAlipayInfoMapper.loadByShopId(dto.getShopId());
            //第1步：获得初始化的AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl,
                    alipayInfo.getAppid(), alipayInfo.getMerchantPrivateKey(), "json",
                    AlipayConfig.charset, alipayInfo.getAlipayPublicKey(), AlipayConfig.sign_type);

            //设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();

            //回调URL地址----何时触发？---支付完成之后，就会由支付宝开放平台进行回调---目的：将支付之后结果返回（支付成功/支付失败（失败原因）
            alipayRequest.setReturnUrl(AlipayConfig.return_url);
            //回调地址----支付通知---通知用户
            alipayRequest.setNotifyUrl(AlipayConfig.notify_url);


            /** ************************** 下面的参数，是与系统业务关联 ******************* */
            //商户订单号，商户网站订单系统中唯一订单号，必填(这个订单号，是我们自己系统来生成)
            String out_trade_no = dto.getOut_trade_no();
            //付款金额，必填（单位：分。所以金额是都没有小数的。金额的支付只会保留2位小数）
            Double total_amount = dto.getMoney();
            //订单名称，必填：每次支付，订单不允许重复。所以需要自动生成
            String subject = dto.getSubject();
            //商品描述，可空
            String body = dto.getSubjectDesc();

            //下面这种封装参数的方式，是可以使用fastjson进行替换
            AlipayBean alipayBean = new AlipayBean();
            alipayBean.setOut_trade_no(out_trade_no);
            alipayBean.setSubject(subject);
            alipayBean.setTotal_amount(total_amount + "");
            alipayBean.setBody(body);
            //将上面的对象转为json字符串
            alipayRequest.setBizContent(JSONObject.toJSONString(alipayBean));

//            alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
//                    + "\"total_amount\":\"" + total_amount + "\","
//                    + "\"subject\":\"" + subject + "\","
//                    + "\"body\":\"" + body + "\","
//                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

            //向支付宝开放平台发送请求（就是支付宝返回的 支付界面url地址）--->这个返回的结果是一段  html代码片段
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            System.out.println(result);
            return result;
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return "";
    }
}
